(ns amsi.client.main
  (:require [amsi.common.logging :as logger])
  (:require [amsi.common.socket :as socket]))

(import (java.net Socket))

(import (java.io BufferedInputStream PrintWriter InputStreamReader BufferedReader))

(import (java.util Scanner))

(def port 5432)

(def host "127.0.0.1")

 (defn listen-server
   "Reads and prints messages from stream"
   [in]   
     (let [input (.readLine in)]
       (if (nil? input)
         nil         
         ( logger/log "new msg:" input))
      (recur in)))
     
 (defn start-client-agent
   "Starts client agent. In is a stream and listen-server fn for handling the stream"
   [in listen-server]   
   (let [client-agent (agent in)]
     (send client-agent listen-server)))
 
 (logger/log "connecting to server")
 
 (def streams (socket/open-socket (Socket. host port)))
 
 (start-client-agent (:in streams) listen-server)
 
 (def scanner (Scanner.(. System in)))
 
 (read-line)

(loop[]
  (logger/log "enter message: ")
  (flush)
  (let[input (read-line) out (:out streams) ]
    (.println out input)
    (.flush out)
    (recur)))



